package com.geeklan.base.network;
import android.content.Context;
import android.net.ConnectivityManager;
import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public class NetworkMonitor {
    private final Context context;
    private final CompositeDisposable disposables = new CompositeDisposable();
    private NetworkCallBack mNetworkCallBack;
    public NetworkMonitor(Context context,NetworkCallBack networkCallBack) {
        this.context = context;
        this.mNetworkCallBack = networkCallBack;
        startNetworkMonitoring();
    }

    public void startNetworkMonitoring() {
        // 监听网络连接状态（有网或无网）
        disposables.add(ReactiveNetwork.observeNetworkConnectivity(context)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(connectivity -> {
                    boolean isConnected = connectivity.available();
                    if(mNetworkCallBack != null) {
                        mNetworkCallBack.networkStatus(isConnected);
                    }
//                    if (isConnected) {
//                        System.out.println("Network is available");
//                    } else {
//                        System.out.println("Network is unavailable");
//                    }
                }));

        // 可选：监听网络连接类型（Wi-Fi 或蜂窝数据）
        disposables.add(ReactiveNetwork.observeNetworkConnectivity(context)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(connectivity -> connectivity.type()) // 获取连接类型
                .distinctUntilChanged() // 当类型变化时才触发事件
                .subscribe(type -> {
                    if(mNetworkCallBack != null) {
                        mNetworkCallBack.networkType(type);
                    }

                    if (type == ConnectivityManager.TYPE_WIFI) {
                        System.out.println("Connected to Wi-Fi");
                    } else if (type == ConnectivityManager.TYPE_MOBILE) {
                        System.out.println("Connected to Mobile Data");
                    } else {
                        System.out.println("Connected to other network type");
                    }
                }));
    }

    public void stopNetworkMonitoring() {
        // 解除订阅，防止内存泄漏
        disposables.clear();
    }

    public interface NetworkCallBack{
        void networkStatus(boolean isConnected);
        void networkType(int type);
    }
}
